﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;

namespace Acms.AcmsControls.ContentControls.Admin
{
    public class RelatedPostsAdminDisplay : BaseAdminDisplay<RelatedPostsContentControlProperties>
    {
        Telerik.Web.UI.RadGrid grid;

        protected override void CreateChildControls()
        {
            Acms.WebControls.RadGridTextBoxColumn nameCol = new Acms.WebControls.RadGridTextBoxColumn();
            nameCol.DataField = "DisplayName";
            nameCol.HeaderText = "Post";

            Acms.WebControls.RadGridTextBoxColumn pathCol = new Acms.WebControls.RadGridTextBoxColumn();
            pathCol.DataField = "Path";
            pathCol.HeaderText = "Path";

            Acms.WebControls.RadGridSequenceColumn seqCol = new Acms.WebControls.RadGridSequenceColumn();

            grid = new Telerik.Web.UI.RadGrid();
            grid.MasterTableView.Columns.Add(nameCol);
            grid.MasterTableView.Columns.Add(pathCol);
            grid.MasterTableView.Columns.Add(seqCol);

            grid.AutoGenerateColumns = false;
            grid.ShowHeader = false;
            grid.ItemCommand += new Telerik.Web.UI.GridCommandEventHandler(grid_ItemCommand);

            this.Controls.Add(grid);

            base.CreateChildControls();
        }

        void grid_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == "MoveUp" || e.CommandName == "MoveDown")
            {
                int change = e.CommandName == "MoveUp" ? -1 : 1;
                EnsureDataLoaded();
                Properties.Move(e.Item.DataSetIndex, e.Item.DataSetIndex + change);
                ForceSave(GetControl(), Properties);
                grid.DataSource = Properties.GetPosts(SiteId, base.SiteVersion);
                grid.DataBind();
                grid.SelectedIndexes.Clear();
                grid.SelectedIndexes.Add(e.Item.ItemIndex + change);
            }
        }

        public override void DataBind()
        {
            EnsureChildControls();
            if (Properties != null)
            {
                grid.DataSource = Properties.GetPosts(SiteId, base.SiteVersion);
                grid.DataBind();
            }
        }

        protected override string GetCssClass
        {
            get { return "relatedPosts"; }
        }

    }
}
